/**
 * 学生相关API接口
 */

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8086';

// 通用请求函数（兼容 code 为 0 或 200 的业务成功）
const request = async (url: string, options: RequestInit = {}) => {
  const response = await fetch(`${API_BASE_URL}${url}`, {
    headers: {
      'Content-Type': 'application/json',
      ...(options.headers || {}),
    },
    credentials: 'include',
    ...options,
  });

  const contentType = response.headers.get('content-type') || '';
  let result: any;
  if (contentType.includes('application/json')) {
    result = await response.json();
  } else {
    const text = await response.text();
    try {
      result = JSON.parse(text);
    } catch {
      result = { code: response.status, message: text, data: null };
    }
  }

  if (!response.ok) {
    throw new Error(result?.message || `HTTP ${response.status}`);
  }

  if (typeof result?.code !== 'undefined' && ![0, 200].includes(result.code)) {
    const error = new Error(result.message || '请求失败');
    (error as any).code = result.code;
    throw error;
  }

  return result;
};

export interface MyCourseFormDto {
  id: number;
  courseId: number;
  courseName: string;
  isPaid: number;
  createTime: string;
}

export const studentApi = {
  // 获取当前登录用户的报名课程（传 userId 校验一致性）
  getEnrolledCourses: (userId: number): Promise<{ code: number; data: MyCourseFormDto[]; message?: string }> => {
    const token = localStorage.getItem('token');
    return request(`/stu/course/enrolled?userId=${userId}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });
  },
};

export default studentApi;